import 'dart:async';
import 'dart:ui' as ui;

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';


class ZLImg extends StatelessWidget {
  final String image;
  final double? width;
  final double? height;
  final BoxFit? fit;

  const ZLImg({
    super.key,
    required this.image,
    this.width,
    this.height,
    this.fit,
  });

  @override
  Widget build(BuildContext context) {
    return Image.asset(
      image,
      width: width,
      height: height,
      fit: fit ?? BoxFit.fill,
    );
  }
}



//带点击事件的image
class ZLTapImg extends StatelessWidget {
  final String image;
  final Function onTap;
  final double? width;
  final double? height;
  final BoxFit? fit;

  const ZLTapImg({
    super.key,
    required this.image,
    required this.onTap,
    this.width,
    this.height,
    this.fit,
  });

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        FocusManager.instance.primaryFocus?.unfocus();
        onTap();
      },
      child: Image.asset(
        image,
        width: width,
        height: height,
        fit: fit,
      ),
    );
  }
}

class ColoredImage extends StatefulWidget {
  const ColoredImage({
    super.key,
    required this.assetPath,
    required this.color,
  });
  final String assetPath;
  final Color color;

  @override
  createState() => _ColoredImageState();
}

class _ColoredImageState extends State<ColoredImage> {
  ui.Image? _image;

  @override
  void initState() {
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((timestamp) {
      _loadImage();
    });
  }

  Future<void> _loadImage() async {
    final ByteData data = await rootBundle.load(widget.assetPath);
    final Uint8List bytes = data.buffer.asUint8List();
    final ui.Codec codec = await ui.instantiateImageCodec(bytes);
    final ui.FrameInfo frame = await codec.getNextFrame();
    setState(() {
      _image = frame.image;
    });
  }

  @override
  Widget build(BuildContext context) {
    if (_image != null) {
      return CustomPaint(
        size: Size(_image!.width.toDouble(), _image!.height.toDouble()),
        painter: ColoredImagePainter(_image!, widget.color),
      );
    } else {
      return Container();
    }
  }
}

class ColoredImagePainter extends CustomPainter {
  final ui.Image image;
  final Color color;

  ColoredImagePainter(this.image, this.color);

  @override
  void paint(Canvas canvas, Size size) {
    // 绘制背景颜色
    Paint backgroundPaint = Paint()..color = color;
    canvas.drawRect(
        Rect.fromLTWH(0, 0, size.width, size.height), backgroundPaint);
    // 绘制原图像，并设置混合模式
    Paint imagePaint = Paint()..blendMode = BlendMode.dstIn; // 使用dstIn模式来实现掩码效果
    canvas.drawImage(image, Offset.zero, imagePaint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return false;
  }
}
